package com.workingpub.commons.datasource.internal;

import javax.sql.XADataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import com.workingpub.commons.datasource.ConfigProperties;
import com.workingpub.commons.datasource.XADataSourceBuilder;

public abstract class AbstractXADataSourceBuilder implements XADataSourceBuilder {
	protected final Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public XADataSource build(ConfigProperties config) {
		Assert.notNull(config, "Datasource config properties instance is null");
		Assert.hasText(config.getDomain(), "The data source domain property is null or empty.");
		Class<?> driverClass = null;
		try {
			driverClass = Class.forName(config.getDriverClass());
		} catch (ClassNotFoundException e) {
			Assert.isNull(e, "Failed to build XADataSource : " + e.getMessage());
		}
		Assert.isTrue(XADataSource.class.isAssignableFrom(driverClass),
				"Must be a XADataSource driver class, it is not : " + config.getDriverClass());
		Assert.hasText(config.getJdbcUrl(), "Failed to build XADataSource, jdbc url is null or empty.");
		Assert.hasText(config.getJdbcUser(), "Failed to build XADataSource, jdbc user is null or empty.");

		XADataSource dataSource = null;
		try {
			dataSource = buildXaDatasource(config.getJdbcUrl(), config.getJdbcUser(), config.getJdbcPassword());
		} catch (Throwable ex) {
			logger.error("Build error : " + ex.getMessage(), ex);
			Assert.isNull(ex, ex.getMessage());
		}
		return dataSource;
	}

	protected abstract XADataSource buildXaDatasource(String jdbcUrl, String jdbcUser, String jdbcPassword);

}
